var UserTutorOrder = app.controller('UserTutorOrder', function($rootScope, $scope, $http,$state,$stateParams,$interval,$cordovaFileTransfer,$cordovaProgress,$cordovaDatePicker,UserTutorOrderData,anchorScroll) {
	try{
		
		$rootScope.showf=true;
		$scope.show=false;
		$scope.nshow=false;
		$rootScope.tab=3;
		$rootScope.title = '我的订单';

		$scope.busy = false;
		$scope.currentPage = 1;
		$scope.limit = 10;
		$scope.pages = 1;
		
		$scope.log_id=0;
		$scope.vs=0;
		try{
			//视频连线登录
			easemobchat.login(
					{username:JSON.parse(window.localStorage.user).CHATUSER,password:'123456'},
					function(s){
						//window.plugins.toast.showShortCenter(s);
						s= JSON.parse(s);
						console.log(s);
						if(s.type=="ACCEPTED"){
							var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=log&id="+$scope.vs;
							$http.jsonp(url).success(function(data) {
								if(data.done){
									$scope.log_id=data.retval;
								}
							});
						}
						if(s.type=="UPDATE"){
							if($scope.log_id>0){
								var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=logup&id="+$scope.log_id+"&t="+s.time;
								$http.jsonp(url).success(function(data) {
									if(data.done){
										$scope.log_id=data.retval;
									}
								});
							}
						}
						if(s.type=="HANGUP"){
							if($scope.log_id>0){
								var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=logup&id="+$scope.log_id+"&t="+s.time;
								$http.jsonp(url).success(function(data) {
									if(data.done){
										$scope.log_id=data.retval;
									}
								});
								
								
							}
							
							
							if(s.path!=null&&s.path!=''){
								$scope.uploadvideo(s.path);
							}
						}
					},
					function(e){console.log(e);}
			);
		}
		catch(e){showcatch(e);}
		
		
		//播放视频
		$scope.playvideo = function(path){
			if(path){
				videoplay($rootScope.site+path);
			}
		}
		
		//上传视频
		$scope.uploadvideo=function(path){
			if(path==null||path==''){
				showtoast('文件不存在');
				return;
			}
			var imageURI=path;
			var url = $rootScope.site + "index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";
            $http.jsonp(url).success(function (data) {
                console.log(data);
                if (data.done) {
                    $rootScope.ECM_ID = data.retval.userid;
                    $rootScope.HTTP_USER_AGENT = data.retval.HTTP_USER_AGENT;
                    var uri = $rootScope.site + 'index.php?app=appuploadvideo&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';
                    console.log(uri);
                    var options = new FileUploadOptions();
                    options.fileKey = "file";
                    options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
                    options.mimeType = "text/plain";
                    var params = {};
                    params.ECM_ID = $rootScope.ECM_ID;
                    params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
                    params.belong = 5;
                    params.item_id = $scope.vs;
                    options.params = params;
                    ProgressIndicator.showProgressBar('正在上传...');
                    $cordovaFileTransfer.upload(uri, imageURI, options).then(function (r) {
                        console.log("Code = " + r.responseCode);
                        console.log("Response = " + r.response);
                        console.log("Sent = " + r.bytesSent);
                        ProgressIndicator.hide();
                        data = JSON.parse(r.response);
                        if (data.done) {
                        	console.log("id:" + $scope.vs+",path:"+data.retval.file_path);
                            url = $rootScope.site + "index.php?app=usermyapp&act=upconsultvideo&id="+$scope.vs+"&path=" + data.retval.file_path + "&callback=JSON_CALLBACK";
                            $http.jsonp(url).success(function (data) {
                                showtoast('上传成功');
                            });
                        }
                        else {
                            showtoast(data.msg);
                        }
                    }, function (error) {
                        console.log("An error has occurred: Code = " + error.code);
                        console.log("upload error source " + error.source);
                        console.log("upload error target " + error.target);
                        ProgressIndicator.hide();
                        showtoast('上传失败，' + error);
                    }, function (progressEvent) {
                        ProgressIndicator.setProgress(progressEvent.loaded / progressEvent.total);
                    });
                }
            });
		}

		//加载订单列表信息
		$scope.busy = true;
		$scope.order=[];
		$scope.status=$stateParams.status;
		var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=order&status="+$stateParams.status;
		$http.jsonp(url).success(function(data) {
			$scope.order=data.retval.data;
			$scope.busy = false;
			if($scope.order.length>0){
				for(var i=0;i<$scope.order.length;i++){

					if($scope.order[i].timeready!=undefined &&$scope.order[i].timeready>0){
						$scope.djs(i);						
					}
				}
			}
			$scope.pages = Math.ceil(data.retval.total/$scope.limit);
			
			var id=$stateParams.id;
			if(id>0){
				setTimeout(function(){
					anchorScroll.toView('#'+id, true);
				},500);
			}
		});

		$rootScope.$on('$cordovaChat:ChatMessageReciveOrtherEventTutor', function (event, msg) {
			try {
				console.log('$cordovaChat:ChatMessageReciveOrtherEventTutor',msg);
				var d = JSON.parse(window.localStorage.user);
				if(msg.touser==d.CHATUSER){
					var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=order&status="+$stateParams.status;
					$http.jsonp(url).success(function(data) {
						$scope.order=data.retval.data;
						if($scope.order.length>0){
							for(var i=0;i<$scope.order.length;i++){

								if($scope.order[i].timeready!=undefined &&$scope.order[i].timeready>0){
									$scope.djs(i);						
								}
							}
						}
						$scope.pages = Math.ceil(data.retval.total/$scope.limit);
					});
				}
			} catch (e) {
				showcatch(e);
			}
		});

		var timelist=[];
		$scope.djs=function(i){
			for(var j=0;j<timelist.length;j++){
				if(timelist[j].k==i){
					$interval.cancel(timelist[j].t);
					break;
				}
			}
			console.log(timelist);
			console.log(i);
			var timer =  $interval(function(){
				var c=$scope.order[i].timeready;
				$scope.order[i].h=parseInt(c/(60*60));
				if($scope.order[i].h<10){
					$scope.order[i].h='0'+$scope.order[i].h;
				}
				$scope.order[i].m=parseInt((c%(60*60))/60);
				if($scope.order[i].m<10){
					$scope.order[i].m='0'+$scope.order[i].m;
				}
				$scope.order[i].s=parseInt((c%(24*60*60))%60);
				if($scope.order[i].s<10){
					$scope.order[i].s='0'+$scope.order[i].s;
				}
				$scope.order[i].timeready--;

				if($scope.order[i].timeready<=0){
					for(var j=0;j<timelist.length;j++){
						if(timelist[j].k==i){
							$interval.cancel(timelist[j].t);
						}
					}
				}
			},1000);
			timelist.push({"k":i,"t":timer});
		}
		
		
		//展开点击
		$scope.zanclick=function(s){
			$scope.order[s.$index].hh=Math.abs(Math.abs($scope.order[s.$index].hh)-1);
		}

		//接受咨询
		$scope.accept=function(s){
			var n=s.o;
			var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=accept&t="+n.th+"&id="+n.consult_tid;
			$http.jsonp(url).success(function(data) {
				if(data.done){
					showcatch(data.msg);

					$scope.order[s.$index]=data.retval.o;
					$scope.order[s.$index].nshow=true;
					$rootScope.orthermsg(data.retval.push);
				}
			});
		}

		//加载更多
		$scope.loadMore = function() {
			try{
				if ($scope.currentPage < $scope.pages) {

					if ($scope.busy) {
						return false; 
					}
					$scope.busy = true;
					$scope.currentPage++;

					var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=order&status="+$stateParams.status+"&page="+$scope.currentPage;
					$http.jsonp(url).success(function(data) {
						for (var i in data.retval.data) {
							if(typeof data.retval.data[i]!="function")
								$scope.order.push(data.retval.data[i]);
						}
						$scope.pages = Math.ceil(data.retval.total/$scope.limit);

						$scope.busy = false;
						if($scope.pages<=$scope.currentPage){
							//$scope.alerts = [{type : 'success' , msg : '没有更多内容了'}]
						}
					});
				}
			}
			catch (e) {
				showcatch(e);
			}
		};


		$scope.videostart=function(s){
			try{
				var n=s.o;
				if(n.status!=30||n.timeready>0){
					return false;
				}

				var url=SITE_URL+"index.php?app=basetutorapp&callback=JSON_CALLBACK&act=userleft&id="+n.consult_tid;
				$http.jsonp(url).success(function(data) {
					if(data.done){
						console.log(data.retval);
						if(data.retval.time>0){
							easemobchat.videostart(
									{username:data.retval.u,maxtime:data.retval.time,lasttime:30,time0:120,timeval0:'请在8分钟内讲出部分干货，以鼓励学员继续咨询',
										time1:28*60,timeval1:'请注意把控进度，视频已接近30分钟'},
										function(s){console.log(s);$scope.vs=n.consult_tid},
										function(e){console.log(e);}
							);
						}else{
							showtoast("用户余额不足");
						}
					}
				});
			}catch(e){showcatch(e);}
		}

		//播放语音
		$scope.play = function(s){
			try{
				var vp=$scope.order[s.$index].voice_path;
				if(vp!=null&&vp!=''){
					//播放音频 m 即为音频地址
					if($rootScope.media!=undefined&&$rootScope.media!=null){
						$scope.order[s.$index].playm="video.png";
						$rootScope.media.release();

					}
					$rootScope.media=audioplay($rootScope.site+vp);
					console.log('newplay');
					console.log($rootScope.media.src);
					$rootScope.media.successCallback=function(){
						$scope.order[s.$index].playm="video.png";
						console.log('successCallback png');
						console.log($scope.order[s.$index].playm);
						$scope.$apply();
					};
					$rootScope.media.errorCallback=function(err){
						$scope.order[s.$index].playm="video.png";
						console.log('successCallback png');
						console.log($scope.order[s.$index].playm);
						$scope.$apply();
					};

					$scope.order[s.$index].playm="write_d.gif";
					console.log('newplay png');
					console.log($scope.order[s.$index].playm);
					$rootScope.media.play();
				}
			}
			catch(e){
				console.log('play');
				console.log(e);
			}
		}
		
		
		//播放评价语音
		$scope.playeva = function(s){
			try{
				var vp=$scope.order[s.$index].evaluation_voice;
				if(vp!=null&&vp!=''){
					//播放音频 m 即为音频地址
					if($rootScope.media!=undefined&&$rootScope.media!=null){
						$scope.order[s.$index].playeva="video.png";
						$rootScope.media.release();

					}
					$rootScope.media=audioplay($rootScope.site+vp);
					console.log('newplay');
					console.log($rootScope.media.src);
					$rootScope.media.successCallback=function(){
						$scope.order[s.$index].playeva="video.png";
						console.log('successCallback png');
						console.log($scope.order[s.$index].playeva);
						$scope.$apply();
					};
					$rootScope.media.errorCallback=function(err){
						$scope.order[s.$index].playeva="video.png";
						console.log('successCallback png');
						console.log($scope.order[s.$index].playeva);
						$scope.$apply();
					};

					$scope.order[s.$index].playeva="write_d.gif";
					console.log('newplay png');
					console.log($scope.order[s.$index].playeva);
					$rootScope.media.play();
				}
			}
			catch(e){
				console.log('play');
				console.log(e);
			}
		}

		//更改咨询时间
		$scope.upconsulttime = function(s){

			if($scope.order!=null&&$scope.order[s.$index]!=null&&$scope.order[s.$index].th!=null&&$scope.order[s.$index].status==10){
				var mdate=$scope.order[s.$index].th;
				if(mdate==''){
					datetim=new Date();
					timedate=new Date(datetim.getFullYear()+"/"+(datetim.getMonth()+1)+"/"+datetim.getDate()+" "+datetim.getHours()+":"+datetim.getMinutes());
				}else{
					timedate=new Date(mdate);
				}
				var options = {
						date: timedate,
						mode: 'datetime', // or 'time'
						doneButtonLabel: '确定',
						doneButtonColor: '#000000',
						cancelButtonLabel: '取消',
						cancelButtonColor: '#000000'
				};
				$cordovaDatePicker.show(options).then(function(date){
					var year=date.getFullYear();
					var month=date.getMonth()+1;
					var day=date.getDate();
					var hour=date.getHours();
					var minute=date.getMinutes();

					if(month<10){
						month="0"+month;
					}
					if(day<10){
						day="0"+day;
					}
					if(hour<10){
						hour="0"+hour;
					}
					if(minute<10){
						minute="0"+minute;
					}

					datetim=new Date();
					var mmonth=datetim.getMonth()+1;
					var mday=datetim.getDate();
					var mhour=datetim.getHours();
					var mminute=datetim.getMinutes();
					if(mmonth<10){
						mmonth="0"+mmonth;
					}
					if(mday<10){
						mday="0"+mday;
					}
					if(mhour<10){
						mhour="0"+mhour;
					}
					if(mminute<10){
						mminute="0"+mminute;
					}
					var beginTime=datetim.getFullYear()+"-"+mmonth+"-"+mday+" "+mhour+":"+mminute;
					var endTime=date.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
					console.log(beginTime);
					console.log(endTime);
					if($scope.comptime(beginTime,endTime)){
						$scope.order[s.$index].th=date.getFullYear()+"/"+month+"/"+day+" "+hour+":"+minute;
						$scope.order[s.$index].t=month+"月"+day+"日 "+hour+":"+minute;
					}
				});


			}
		};


		//重置
		$scope.resettime = function(s){
			if($scope.order!=null&&$scope.order[s.$index]!=null&&$scope.order[s.$index].tutor!=null){
				var mdate=$scope.order[s.$index].tutor.start_time;
				if(mdate==''){
					datetim=new Date();
					timedate=new Date(datetim.getFullYear()+"/"+(datetim.getMonth()+1)+"/"+datetim.getDate()+" "+datetim.getHours()+":"+datetim.getMinutes());
				}else{
					timedate=new Date(mdate);
				}
				var options = {
						date: timedate,
						mode: 'datetime', // or 'time'
						doneButtonLabel: '确定',
						doneButtonColor: '#000000',
						cancelButtonLabel: '取消',
						cancelButtonColor: '#000000'
				};
				$cordovaDatePicker.show(options).then(function(date){
					var year=date.getFullYear();
					var month=date.getMonth()+1;
					var day=date.getDate();
					var hour=date.getHours();
					var minute=date.getMinutes();

					if(month<10){
						month="0"+month;
					}
					if(day<10){
						day="0"+day;
					}
					if(hour<10){
						hour="0"+hour;
					}
					if(minute<10){
						minute="0"+minute;
					}

					datetim=new Date();
					var mmonth=datetim.getMonth()+1;
					var mday=datetim.getDate();
					var mhour=datetim.getHours();
					var mminute=datetim.getMinutes();
					if(mmonth<10){
						mmonth="0"+mmonth;
					}
					if(mday<10){
						mday="0"+mday;
					}
					if(mhour<10){
						mhour="0"+mhour;
					}
					if(mminute<10){
						mminute="0"+mminute;
					}
					var beginTime=datetim.getFullYear()+"-"+mmonth+"-"+mday+" "+mhour+":"+mminute;
					var endTime=date.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
					console.log(beginTime);
					console.log(endTime);
					if($scope.comptime(beginTime,endTime)){

						var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=updateordertime&id="+$scope.order[s.$index].consult_tid+"&date="+endTime;
						$http.jsonp(url).success(function(data) {
							if(data.done){
								showtoast(data.msg);
								$scope.order[s.$index]=data.retval.consult;
								$scope.djs(s.$index);
								$rootScope.orthermsg(data.retval.push);
							}
						});
					}
				});


			}
		};
		//时间比较
		$scope.comptime=function(beginTime,endTime) {
			try {
				var beginTimes = beginTime.substring(0, 10).split('-');
				var endTimes = endTime.substring(0, 10).split('-');

				beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
				endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);

				var a = (Date.parse(endTime) - Date.parse(beginTime)) / 3600 / 1000;
				if (a < 0) {
					showtoast('选择时间不能小于当前时间');
					return false;
				} else if (a > 0) {
					return true;
				} else if (a == 0) {
					showtoast('选择时间不能小于当前时间');
					return false;
				} else {
					return false;
				}
			} catch (e) {
				console.log(e);
			}

		}
	}
	catch (e) {
		showcatch(e);
	}
});
UserTutorOrder.UserTutorOrderData=function($q, $http,$stateParams,$rootScope){
	try {
		var data = [];
		var def = $q.defer();
		if(window.localStorage.u==undefined||window.localStorage.u==null||window.localStorage.u==""){			
			$rootScope.go("loginmain");
		}else{
			def.resolve(data);
		}

		return def.promise;
	} catch (e) {
		showcatch(e);
	}
}